package net.vsame.url2sql.helper;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.domain.UrlConfig;
import net.vsame.url2sql.web.bigpipe.BigpipeDataHelper;

/**
 * 网页辅助类
 * 2012-7-1 上午9:29:46
 * @author <a href="mailto:gaollg@sina.com">Gaollg</a>
 *
 */
public class WebHelper {
	
	private static ThreadLocal<Url2SqlContext> context = new ThreadLocal<Url2SqlContext>();

	public static void init(HttpServletRequest request, HttpServletResponse response) {
		Url2SqlContext temp = new Url2SqlContext();
		temp.setRequest(request);
		temp.setResponse(response);
		WebHelper.context.set(temp);
	}
	
	public static Url2SqlContext getContext() {
		return context.get();
	}
	/**
	 * 销毁,在每次请求完成后,调用回收
	 */
	public static void remove(){
		Url2SqlContext temp = getContext();
		try {
			if(temp!=null && temp.getConn() != null){
				System.out.println("close conn..........");
				temp.getConn().close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			context.remove();
			BigpipeDataHelper.remove();
		}
	}
	
	/**
	 * 取得Connection
	 * @return
	 */
	public static Connection getConnection() {
		Url2SqlContext temp = getContext();
		if(temp == null){
			temp = new Url2SqlContext();
			context.set(temp);
		}
		return temp.getConn();
	}

	public static String getRestfulParam(int i) {
		return getContext().getRestfulParam(i);
	}
	public static String[] getRestfulParams() {
		return getContext().getRestfulParams();
	}
	public static void setRestfulParam(String target, String restfulParam, UrlConfig c) {
		Url2SqlContext temp = getContext();
		temp.setUrl(target);
		temp.setRestfulParam(restfulParam);
		temp.setUrlConfig(c);
	}
	
}
